package com.extension.company.view.main;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.extension.company.admin.R;
import com.extension.company.model.api.RetrofitUrlApi;
import com.extension.company.model.entity.HotDataListBean;
import com.extension.company.model.entity.ListHeadBean;
import com.extension.company.common.mvp.BaseFragment;
import com.extension.company.common.utils.BDMapUtils;
import com.extension.company.common.utils.DisplayUtils;
import com.extension.company.common.utils.Utils;
import com.extension.company.common.widget.ShapedImageView;
import com.extension.company.contract.main.FragmentHomeContract;
import com.extension.company.presenter.main.FragmentHomePresenter;
import com.extension.company.view.H5.HomeAdListActivity;
import com.extension.company.view.adapter.GirdDropDownAdapter;
import com.extension.company.view.adapter.HomeAdapter;
import com.extension.company.view.home.CityNeedActivity;
import com.extension.company.view.home.MakeMoneyActivity;
import com.extension.company.view.home.hotactivity.HotActivityDetailActivity;
import com.extension.company.view.home.message.MessCenterListActivity;
import com.extension.company.view.home.search.SearchActivity;
import com.extension.company.view.home.TwoCategory;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;

import com.sunfusheng.marqueeview.MarqueeView;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.HotCity;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页的fragment
 */
public class FragmentHome extends BaseFragment<FragmentHomeContract.View, FragmentHomePresenter>
		implements FragmentHomeContract.View,
		View.OnClickListener,
		AdapterView.OnItemClickListener,
		OnRefreshListener,
		OnLoadMoreListener {

	@BindView(R.id.m_top)
	LinearLayout m_top;
	@BindView(R.id.mListView)
	ListView mListView;
	@BindView(R.id.iv_message)
	ImageView iv_message;
	@BindView(R.id.layout_search)
	LinearLayout layout_search;
	@BindView(R.id.title_layout)
	View title_layout;
	@BindView(R.id.tv_address)
	TextView tvAddress;
	@BindView(R.id.fragment_home_refrsh)
	SmartRefreshLayout fragment_home_refrsh;
	@BindView(R.id.fragment_home_title)
	LinearLayout fragment_home_title;
	@BindView(R.id.fragment_home_title_fl)
	FrameLayout frameLayout;
	@BindView(R.id.fragment_home_search_img)
	ImageView fragment_home_search_img;
	@BindView(R.id.fragment_home_search_hint)
	TextView fragment_home_search_hint;

	private Activity activity;
	private View headerview;
	private LinearLayout layout_header_makemoney,
			layout_sellerenter,
			layout_tab1, layout_tab2,
			layout_tab3, layout_tab4, layout_tab5;

	private HomeAdapter adapter;
	private String locationName;
	private ConvenientBanner banner;
	private BDMapUtils baiduMapLocation;
	private ImageView tab1Img;
	private TextView tab1Tv;
	private ImageView tab2Img;
	private TextView tab2Tv;
	private ImageView tab3Img;
	private TextView tab3Tv;
	private ImageView tab4Img;
	private TextView tab4Tv;
	private ImageView tab5Img;
	private TextView tab5Tv;
	private ShapedImageView activity1;
	private ShapedImageView activity2;
	private ShapedImageView activity3;
	private ImageView activity4;
	private TextView activityNotification;
	private MarqueeView marqueeView;
	private Context context;

	private List<String> messages = new ArrayList<>(); // 跑马灯的数据
	private List<HotDataListBean.DataBean.HotDataBean> hotActivityList = new ArrayList<>(); // 热门活动
	private List<ListHeadBean.DataBean.OtherAdBean> AdList; // 三个广告页
	private List<ListHeadBean.DataBean.CateListBean> fiveList;  // 5个item
	private String largeImageUrl;

	@Override
	public void onAttach(Context context) {
		super.onAttach(context);
		this.context = context;
	}

	@Override
	public void onResume() {
		super.onResume();
		if (null != banner) {
			banner.startTurning(4000);
		}

	}

	@Override
	public void onPause() {
		super.onPause();
		if (null != banner) {
			banner.stopTurning();
		}

	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	@Override
	public FragmentHomeContract.View createView() {
		return this;
	}

	@Override
	public FragmentHomePresenter createPresenter() {
		return new FragmentHomePresenter();
	}

	@Override
	public void init() {
		activity = getActivity();
		initView();
		initData();
		initListener();
	}

	@Override
	public int getMainLayout() {
		return R.layout.fragment_index;
	}

	private void initView() {
		initSmartRefresh();
		headerview = LayoutInflater.from(activity).inflate(R.layout.fragment_home_headerview, null);
		mListView.addHeaderView(headerview);
		layout_search.setFocusableInTouchMode(true);

		layout_header_makemoney = getViewById(headerview, R.id.layout_header_makemoney);
		layout_sellerenter = getViewById(headerview, R.id.layout_sellerenter);
		layout_tab1 = getViewById(headerview, R.id.layout_tab1);
		layout_tab2 = getViewById(headerview, R.id.layout_tab2);
		layout_tab3 = getViewById(headerview, R.id.layout_tab3);
		layout_tab4 = getViewById(headerview, R.id.layout_tab4);
		layout_tab5 = getViewById(headerview, R.id.layout_tab5);
		banner = getViewById(R.id.fragment_home_banner);


		tab1Img = getViewById(R.id.tab1_img);
		tab1Tv = getViewById(R.id.tab1_tv);

		tab2Img = getViewById(R.id.tab2_img);
		tab2Tv = getViewById(R.id.tab2_tv);
		tab3Img = getViewById(R.id.tab3_img);
		tab3Tv = getViewById(R.id.tab3_tv);
		tab4Img = getViewById(R.id.tab4_img);
		tab4Tv = getViewById(R.id.tab4_tv);
		tab5Img = getViewById(R.id.tab5_img);
		tab5Tv = getViewById(R.id.tab5_tv);


		activity1 = getViewById(R.id.activity1);
		activity2 = getViewById(R.id.activity2);
		activity3 = getViewById(R.id.activity3);
		activity4 = getViewById(R.id.activity4);

		marqueeView = getViewById(R.id.marqueeView);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) m_top.getLayoutParams();
			layoutParams.height = Utils.getStatusBarHeight(activity);  // 获取手机状态栏高度
			m_top.setLayoutParams(layoutParams);
			m_top.setBackgroundColor(getResources().getColor(R.color.topcolor));
		}
		m_top.setAlpha(1.0f);
		title_layout.setAlpha(1.0f);

	}


	private void initData() {


		adapter = new HomeAdapter(activity, hotActivityList);
		mListView.setAdapter(adapter);

		presenter.requestHeader(activity); // 发送网络请求
		presenter.requestHotData();  // 请求热门活动

		baiduMapLocation = BDMapUtils.getInstance(); // 百度地图的定位
		baiduMapLocation.requestLocation(new BDMapUtils.CityLocationListener() {
			@Override
			public void cityName(String cityName, String name) {
				tvAddress.setText(cityName);
				locationName = name;
				Log.d("zwk", "获取的地址" + locationName);

			}
		});

	}

	/**
	 * 设置smartRefresh
	 */
	private void initSmartRefresh() {
		fragment_home_refrsh.setRefreshHeader(new ClassicsHeader(activity)); // 设置下拉刷新头
		fragment_home_refrsh.setRefreshFooter(new ClassicsFooter(activity)); // 设置上拉加载更多的尾
		fragment_home_refrsh.setEnableHeaderTranslationContent(false); // 下拉时候，刷新的界面不随界面移动
		fragment_home_refrsh.setEnableLoadMore(false);// 禁用上拉加载更多
		fragment_home_refrsh.autoRefresh();  // 进入自动刷新
	}

	private void initListener() {
		layout_search.setOnClickListener(this);
		iv_message.setOnClickListener(this);
		layout_header_makemoney.setOnClickListener(this);
		layout_sellerenter.setOnClickListener(this);
		layout_tab1.setOnClickListener(this);
		layout_tab2.setOnClickListener(this);
		layout_tab3.setOnClickListener(this);
		layout_tab4.setOnClickListener(this);
		layout_tab5.setOnClickListener(this);
		activity1.setOnClickListener(this);
		activity2.setOnClickListener(this);
		activity3.setOnClickListener(this);
		activity4.setOnClickListener(this);


		initListViewOnScrollListener();
		mListView.setOnItemClickListener(this);
		fragment_home_refrsh.setOnRefreshListener(this);
		fragment_home_refrsh.setOnLoadMoreListener(this);


		fragment_home_refrsh.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {  // smartRefresh 根据下拉，隐藏title标题栏
			@Override
			public void onHeaderMoving(RefreshHeader header, boolean isDragging, float percent, int offset, int headerHeight, int maxDragHeight) {
				super.onHeaderMoving(header, isDragging, percent, offset, headerHeight, maxDragHeight);
				Log.d("zwk", "下拉的高度" + percent + "offset" + offset + "headerHeight" + headerHeight + "maxDragHeight" + maxDragHeight);
				m_top.setAlpha(1 - Math.min(percent, 1));
				title_layout.setAlpha(1 - Math.min(percent, 1));
				tvAddress.setAlpha(1 - Math.min(percent, 1));
				layout_search.setAlpha(1 - Math.min(percent, 1));
				iv_message.setAlpha(1 - Math.min(percent, 1));
				fragment_home_search_img.setAlpha(1 - Math.min(percent, 1));
				fragment_home_search_hint.setAlpha(1 - Math.min(percent, 1));
			}
		});
	}

	/**
	 * listView滑动，设置顶部的搜索栏 透明度
	 */
	private void initListViewOnScrollListener() {
		mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				float abs = Math.abs(headerview.getTop());  // 获取listview的header的头部距离手机屏幕最上面的距离
				Log.d("zwk", "abs" + abs);
				int height = DisplayUtils.convertDip2Px(activity, 150);
				if (abs == 1.0f) {
					title_layout.setAlpha(1.0f);  // 标题栏设置透明度，全显示
					m_top.setAlpha(0.0f);         // 状态栏设置全透明
				} else {
					float i = 1.0f / height * abs;   // 随着上滑，abs 值越来越大，i值自增，当abs==height的高度的时候，i=1
					if (i < 1.0f) {       // 随着上滑动
						title_layout.setAlpha(i);  // 标题栏的透明度值接近一，标题栏全部显示出来
						m_top.setAlpha(i);         // 状态栏渐渐的显示出来
					} else {
						title_layout.setAlpha(1.0f);   // 当abs >height 后，状态栏和标题栏都显示出来。
						m_top.setAlpha(1.0f);
					}
				}
			}
		});


	}

	@Override
	public void onClick(View v) {
		Intent activityOneIntent = new Intent(context, HomeAdListActivity.class);
		switch (v.getId()) {
			case R.id.layout_search:
				SearchActivity.startSearchActivity(activity);
				break;
			case R.id.iv_message:
				//消息中心
				MessCenterListActivity.startMessCenterList(activity);
				break;
			case R.id.layout_header_makemoney:
				MakeMoneyActivity.startMakeMoney(activity);
				break;
			case R.id.layout_sellerenter:
				//商家入驻
//				SellerEnterActivity.startActivity(activity);
				CityNeedActivity.startCityNeedActivity(activity);
				break;
			case R.id.layout_tab1:
				TwoCategory.startActivity(activity);
				break;
			case R.id.layout_tab2:
				TwoCategory.startActivity(activity);
				break;
			case R.id.layout_tab3:
				TwoCategory.startActivity(activity);
				break;
			case R.id.layout_tab4:
				TwoCategory.startActivity(activity);
				break;
			case R.id.layout_tab5:
				TwoCategory.startActivity(activity);
				break;
			case R.id.activity1:
				activityOneIntent.putExtra("url", AdList.get(0).getUrl());
				break;
			case R.id.activity2:
				activityOneIntent.putExtra("url", AdList.get(1).getUrl());
				break;
			case R.id.activity3:
				activityOneIntent.putExtra("url", AdList.get(2).getUrl());
				break;
			case R.id.activity4:
				activityOneIntent.putExtra("url", largeImageUrl);
				break;
			default:
				break;
		}
		context.startActivity(activityOneIntent);
	}

	@Override
	public void showLoading() {

	}

	@Override
	public void hideLoading() {

	}

	@Override
	public void onError(Throwable throwable) {

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  // 热门活动的item点击事件
		// 根据数据的不同，跳转不同的界面
//		if (position == 1) {
////			HotEventTopPopularizeActivity.startActivity(activity, 0);
//
//		} else {
//			HotActivityDetailActivity.startActivity(activity, 1);
		Intent intent = new Intent(activity, HotActivityDetailActivity.class);
		HotDataListBean.DataBean.HotDataBean hotDataBean = (HotDataListBean.DataBean.HotDataBean) parent.getAdapter().getItem(position);
		intent.putExtra("type", 1);
		intent.putExtra("goodid", hotDataBean.getGoods_id());
		activity.startActivity(intent);
		//	}

	}

	@OnClick(R.id.tv_address)
	public void onViewClicked() {
		showAddress(locationName);
	}

	/**
	 * 定位城市选择
	 */
	private void showAddress(final String locationName) {
		List<HotCity> hotCities = new ArrayList<>();
		hotCities.add(new

				HotCity("北京", "北京", "101010100")); //code为城市代码
		hotCities.add(new

				HotCity("上海", "上海", "101020100"));
		hotCities.add(new

				HotCity("广州", "广东", "101280101"));
		hotCities.add(new

				HotCity("深圳", "广东", "101280601"));
		hotCities.add(new

				HotCity("杭州", "浙江", "101210101"));
		CityPicker.from(this)
				.enableAnimation(true)
				.setAnimationStyle(R.style.DefaultCityPickerAnimation)
				.setLocatedCity(null)
				.setHotCities(hotCities)
				.setOnPickListener(new OnPickListener() {
					@Override
					public void onPick(int position, City data) {
//						currentTV.setText(String.format("当前城市：%s，%s", data.getName(), data.getCode()));
						Toast.makeText(
								activity,
								String.format("点击的数据：%s，%s", data.getName(), data.getCode()),
								Toast.LENGTH_SHORT)
								.show();
					}

					@Override
					public void onCancel() {
						Toast.makeText(activity, "取消选择", Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onLocate() {
						//开始定位，这里模拟一下定位
						new Handler().postDelayed(new Runnable() {
							@Override
							public void run() {
								CityPicker.from(FragmentHome.this).locateComplete(new LocatedCity(locationName, "广东", "101280601"), LocateState.SUCCESS);
							}
						}, 3000);

					}
				})
				.show();
	}


	@Override
	public void onRefresh(@NonNull RefreshLayout refreshLayout) {  // 下拉刷新
		refreshLayout.finishRefresh(2000);

	}


	@Override
	public void onLoadMore(@NonNull RefreshLayout refreshLayout) {  // 上拉加载更多
		refreshLayout.finishLoadMore(2000);

	}

	/**
	 * 轮播图相关设置
	 */
	public void initBanner(List<ListHeadBean.DataBean.BannerBean> list) {

		List<String> imgUrls = new ArrayList<>();
		for (ListHeadBean.DataBean.BannerBean bean : list) {
			imgUrls.add("http://www.17xiangke.cn/" + bean.getUrl());
		}

		banner.setPageIndicator(new int[]{R.drawable.index_white, R.drawable.index_red});
		banner.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);

		banner.setPages(new CBViewHolderCreator() {
			@Override
			public Holder createHolder(View itemView) {
				return new FragmentHomeHolderView(itemView);
			}

			@Override
			public int getLayoutId() {
				return R.layout.fragment_home_banner_item;
			}
		}, imgUrls);
	}


	/**
	 * banner加载网络图片
	 */
	public class FragmentHomeHolderView extends Holder<String> {
		private ImageView imgeView;

		public FragmentHomeHolderView(View itemView) {
			super(itemView);
		}

		@Override
		protected void initView(View itemView) {
			imgeView = itemView.findViewById(R.id.fragment_home_item_img);
		}

		@Override
		public void updateUI(String data) {
			RequestOptions requestOptions = new RequestOptions().placeholder(R.drawable.addimg_1x).error(R.drawable.banneilh).dontAnimate();
			Glide.with(activity).load(data).listener(new RequestListener<Drawable>() {
				@Override
				public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
					return false;
				}

				@Override
				public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
					return false;
				}
			}).apply(requestOptions).into(imgeView);
		}
	}


	@Override
	public void initBannerData(List<ListHeadBean.DataBean.BannerBean> list) { // 轮播图数据
		initBanner(list);
	}

	@Override
	public void initImgAd(List<ListHeadBean.DataBean.OtherAdBean> list) {  // 三个广告位图片
		this.AdList = list;
//		RequestOptions
//				requestOptions = new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10))
//				.placeholder(R.mipmap.cp_icon_empty)
//				.error(R.mipmap.cp_icon_empty)
//				.dontAnimate();
		Glide.with(activity).load(RetrofitUrlApi.BaseHostUrl + list.get(0).getImage())
//				.apply(requestOptions)
				.into(activity1);
		Glide.with(activity).load(RetrofitUrlApi.BaseHostUrl + list.get(1).getImage())
//				.apply(requestOptions)
				.into(activity2);
		Glide.with(activity).load(RetrofitUrlApi.BaseHostUrl + list.get(2).getImage())
//				.apply(requestOptions)
				.into(activity3);

	}

	@Override
	public void initImgLarge(ListHeadBean.DataBean.AdDataBean ADBean) {  // 大横幅广告
		this.largeImageUrl = ADBean.getUrl();
		Glide.with(context).load(RetrofitUrlApi.BaseHostUrl + ADBean.getImage()).into(activity4);
	}

	@Override
	public void initHorselight(List<ListHeadBean.DataBean.FirstDataBean> list) { // 走马灯活动通知
		for (int i = 0; i < list.size(); i++) {
			messages.add(list.get(i).getContent());
		}
		marqueeView.startWithList(messages);
	}

	@Override
	public void initFiveItem(List<ListHeadBean.DataBean.CateListBean> list) { // 5个item
		this.fiveList = list;
		RequestOptions requestOptions = new RequestOptions()
				.transforms(new CenterCrop(), new RoundedCorners(20))
				.placeholder(R.mipmap.ic_launcher)
				.error(R.mipmap.ic_launcher);

//				.override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) // 如果设置了大小，就会按照大小进行设置，即使缩放也不起作用

		Glide.with(context).load(RetrofitUrlApi.BaseHostUrl + list.get(0).getImage()).apply(requestOptions).into(tab1Img);
		Glide.with(context).load(RetrofitUrlApi.BaseHostUrl + list.get(1).getImage()).apply(requestOptions).into(tab2Img);
		Glide.with(context).load(RetrofitUrlApi.BaseHostUrl + list.get(2).getImage()).apply(requestOptions).into(tab3Img);
		Glide.with(context).load(RetrofitUrlApi.BaseHostUrl + list.get(3).getImage()).apply(requestOptions).into(tab4Img);
		Glide.with(context).load(RetrofitUrlApi.BaseHostUrl + list.get(4).getImage()).apply(requestOptions).into(tab5Img);

		tab1Tv.setText(list.get(0).getName());
		tab2Tv.setText(list.get(1).getName());
		tab3Tv.setText(list.get(2).getName());
		tab4Tv.setText(list.get(3).getName());
		tab5Tv.setText(list.get(4).getName());
	}

	@Override
	public void initHotActivity(List<HotDataListBean.DataBean.HotDataBean> list) {  //热门活动
		if (null != hotActivityList) {
			hotActivityList.addAll(list);
			adapter.notifyDataSetChanged();
		}

	}
}
